import axios from 'axios'

// 创建axios实例
const api = axios.create({
    baseURL: '/api', // 代理到后端
    timeout: 15000, // 超时时间延长到15秒
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器 - 添加token（可选）
api.interceptors.request.use(config => {
    // 如果实现了JWT认证，可以这样添加token
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截器 - 统一处理错误
api.interceptors.response.use(
    response => {
        // 直接返回响应数据（去掉axios的包装）
        return response.data
    },
    error => {
        if (error.response) {
            const { status, data } = error.response
            let message = '请求错误'

            // 根据后端返回的错误信息显示
            if (data && typeof data === 'string') {
                message = data
            } else if (data && data.message) {
                message = data.message
            }

            // 更详细的错误分类
            switch (status) {
                case 400:
                    message = `请求参数错误: ${message}`
                    break
                case 401:
                    message = '未授权，请重新登录'
                    // 可以在这里触发登出逻辑
                    break
                case 403:
                    message = '权限不足，拒绝访问'
                    break
                case 404:
                    message = `资源不存在: ${message}`
                    break
                case 500:
                    message = `服务器错误: ${message}`
                    break
                default:
                    message = `请求错误 (${status}): ${message}`
            }

            console.error(`API Error [${status}]:`, message)
            alert(message)
        } else if (error.request) {
            // 请求已发出但没有响应
            console.error('No response received:', error.request)
            alert('网络错误，请检查连接或稍后重试')
        } else {
            // 请求设置错误
            console.error('Request setup error:', error.message)
            alert('请求配置错误: ' + error.message)
        }

        return Promise.reject(error)
    }
)

export const userApi = {
    login: (credentials) => api.post('/users/login', credentials),
    register: (userData) => api.post('/users/register', userData),
    getUserById: (id) => api.get(`/users/${id}`),
    updateUser: (id, userData) => api.put(`/users/${id}`, userData),
    deleteUser: (id) => api.delete(`/users/${id}`)
}

// 商品API
export const productApi = {
    getAll: () => api.get('/products'),
    search: (keyword, category) => api.get('/products/search', {
        params: { keyword, category }
    }),
    getById: (id) => api.get(`/products/${id}`),
    create: (product) => api.post('/products', product),
    update: (id, product) => api.put(`/products/${id}`, product),
    delete: (id) => api.delete(`/products/${id}`)
}

// 购物车API
export const cartApi = {
    getByUser: (userId) => api.get(`/cart/user/${userId}`),
    addItem: (item) => api.post('/cart', item),
    updateQuantity: (id, quantity) => api.put(`/cart/${id}/quantity`, null, {
        params: { quantity } // 使用查询参数传递数量
    }),
    removeItem: (id) => api.delete(`/cart/${id}`),
    clearCart: (userId) => api.delete(`/cart/user/${userId}`)
}

// 订单API
export const orderApi = {
    create: (orderData) => api.post('/orders', orderData),
    getByUser: (userId) => api.get(`/orders/user/${userId}`),
    getAll: () => api.get('/orders'),
    getById: (id) => api.get(`/orders/${id}`),
    updateStatus: (orderId, status) => api.put(`/orders/${orderId}/status`, null, {
        params: { status } // 使用查询参数传递状态
    }),
    cancel: (orderId) => api.put(`/orders/${orderId}/cancel`)
}

// vite.config.js 示例（Vite项目）
//export default
